package cn.wolfcode.thread;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class TestForkJoin {
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();

        Instant start = Instant.now();
        ForkJoinDemo forkJoinDemo = new ForkJoinDemo(0,100000005L);//PT0.036Ssum_5000000450000010
        Long sum = pool.invoke(forkJoinDemo);
        Instant end = Instant.now();
        System.out.println(Duration.between(start,end)+"sum_"+sum);
    }

    @Test
    public void testSerail(){
        Instant start = Instant.now();
        long sum = 0L;
        for (int i = 0; i <100000005L ; i++) {
            sum+= i;
        }
        Instant end = Instant.now();
        System.out.println(Duration.between(start,end)+"sum_"+sum);//PT0.048Ssum_5000000450000010
        //100億算不出來
    }

}

class ForkJoinDemo extends RecursiveTask<Long> {
    private long start;
    private long end;

    public ForkJoinDemo(long start,long end){
        this.start = start;
        this.end = end;
    }
    private static final long BORDER = 100000L;
    protected Long compute() {
        long length = end -start;
        if (length  <= BORDER){
            long sum = 0L;
            for (long i = start; i < end ; i++) {
                sum += i;
            }
            return sum;
        }else {
            long middle = (start + end)/2;
            ForkJoinDemo left = new ForkJoinDemo(start, middle);
            left.fork();
            ForkJoinDemo right = new ForkJoinDemo(middle, end);
            right.fork();
            return left.join() + right.join();

        }
    }
}